<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>04.防抖和节流.html</title>
</head>

<body>
    <button id="btnNode">点击防抖</button>
    <button id="btnNode2">点击节流</button>
    <script>
        console.log(+new Date());
        let t = 0;
        btnNode2.addEventListener("click", handlerClick2());
        function handlerClick2() {
            let t2 = 0;
            return (e) => {
                let start = +new Date();
                if (start - t2 >= 1000) {
                    console.log("####", e);
                    t2 = start;
                }
            }
        }
        console.log("======================");
        // btnNode2.onclick = function (e) {
        //     let start = +new Date();
        //     if (start - t >= 60000) {
        //         console.log("####", e);
        //         t = start;
        //     }
        // }

        console.log("======================");
        function fn01(a) {
            // console.log("####");
            let start = Date.now()
            if (start - t >= 1000) {
                console.log("####", a);
                t = start
            }

        }
        fn01(1)
        fn01(2)
        fn01(3)
        console.log("==========================");
        btnNode.addEventListener("click", handlerClick());
        // 防抖   高阶函数  + 定时器
        function handlerClick() {
            return (e) => {
                if (window.clearTime) {
                    clearTimeout(window.clearTime);
                }
                window.clearTime = setTimeout(() => {
                    console.log("####", e);
                }, 1000);
            };
        }

        // 节点注册事件的方式
        // btnNode.onclick = function(e) {
        //     if(window.clearTime) {
        //         clearTimeout(window.clearTime)

        //     }

        //     window.clearTime = setTimeout(() => {
        //         console.log("####",e);
        //     },1000)

        // }
        // 防抖
        // function fn() {
        //     console.log("####");
        // }
        // fn()
        // fn()
        // fn()
        // 1s之内只执行一次
        function fn(a) {
            if (window.clearTime) {
                clearTimeout(window.clearTime);
            }
            window.clearTime = setTimeout(() => {
                console.log("####", a);
            }, 1000);
        }
        fn(1);
        fn(2);
        fn(3);
    </script>
</body>

</html>